package edu.friday.Service.Impl;


import edu.friday.Service.SysUserService;
import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.SysUser;
import edu.friday.model.vo.SysUserVO;
import edu.friday.repository.SysUserRepository;
import edu.friday.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserRepository sysUserRepository;

    @Override
    public TableDataInfo selectUserList(SysUserVO userVO, Pageable pageable) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyPropertiesIgnoreEmpty(userVO, sysUser);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phonenumber", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<SysUser> example = Example.of(sysUser, exampleMatcher);
        Page<SysUser> page = sysUserRepository.findAll(example, pageable);
        return TableDataInfo.success(page.toList(), page.getTotalElements());

    }

    @Override
    @Transactional
    public boolean insertUser(SysUserVO sysUserVO){
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserVO, sysUser);
        sysUser.setDelFlag("0");
        sysUserRepository.save(sysUser);
        sysUserVO.setUserId(sysUser.getUserId());
        insertUserRole(sysUserVO);
        return null != sysUser.getUserId();
    }

    @Transactional
    public int insertUserRole(SysUserVO sysUserVO){
        Long[] roles = sysUserVO.getRoleIds();
        if (roles == null || roles.length == 0) {
            return 0;
        }
        Long[] userIds = new Long[roles.length];
        Arrays.fill(userIds, sysUserVO.getUserId());
        return sysUserRepository.batchInsertUserRole(userIds,roles);
    }

    @Override
    public String checkUserNameUnique(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        return checkAction(sysUser);
    }
    String checkAction(SysUser sysUser){
        Long userId = sysUser.getUserId();
        sysUser.setUserId(null);
        SysUser info = findOne(sysUser);
        //新增时，sysUser的id为空，修改时不为空
        if (null == userId ) {
            if (null != info) {
                return UserConstants.NOT_UNIQUE;
            }else {
                return UserConstants.UNIQUE;
            }
        }else {
            if (info == null || userId.equals(info.getUserId())) {
                return UserConstants.UNIQUE;
            }else {
                return UserConstants.NOT_UNIQUE;
            }
        }
//        return UserConstants.UNIQUE;
    }
    private SysUser findOne(SysUser sysUser) {
        Example<SysUser> example = Example.of(sysUser);
        List<SysUser> list = sysUserRepository.findAll(example, PageRequest.of(0,1)).toList();
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);
    }

    @Override
    public String checkEmailUnique(SysUserVO sysUserVO){
        if (null == sysUserVO.getEmail()) {
            return UserConstants.UNIQUE;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(sysUserVO.getUserId());
        sysUser.setEmail(sysUserVO.getEmail());
        return checkAction(sysUser);
    }
    @Override
    public String checkPhoneUnique(SysUserVO sysUserVO){
        if (null == sysUserVO.getPhoneNumber()){
            return UserConstants.NOT_UNIQUE;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(sysUserVO.getUserId());
        sysUser.setPhoneNumber(sysUserVO.getPhoneNumber());
        return checkAction(sysUser);
    }

    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
          return sysUserRepository.deleteUserByIds(userIds);
//        int sum = 0;
//        for (Long userId : userIds) {
//            SysUser sysUser = new SysUser();
//            if(sysUserRepository.existsById(userId)){
//                sysUserRepository.deleteById(userId);
//                sysUserRepository.deleteUserByIds(userId);
//                sum++;
//            }
//        }

    }

    @Override
    @Transactional
    public boolean updateUser(SysUserVO userVO){
        Long userId = userVO.getUserId();
        if (!sysUserRepository.existsById(userVO.getUserId())) {
            return false;
        }
        sysUserRepository.deleteUserRoleByUserId(userId);
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVO, sysUser);
        sysUserRepository.save(sysUser);
        insertUserRole(userVO);
        return null != sysUser.getUserId();
    }

    @Override
    public SysUser selectUserById(Long userId) {
//        return sysUserRepository.findById(userId).orElse(null);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDelFlag("0");
        return findOne(sysUser);
    }

    @Override
    public SysUser selectUserByName(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setDelFlag("0");
        return findOne(sysUser);
    }

}
